package com.longy.gulimall.product.service.impl;

import com.longy.common.constant.ProductConstant;
import com.longy.common.utils.PageUtils;
import com.longy.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.longy.gulimall.product.dao.AttrGroupDao;
import com.longy.gulimall.product.dao.CategoryDao;
import com.longy.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.longy.gulimall.product.entity.AttrGroupEntity;
import com.longy.gulimall.product.entity.CategoryEntity;
import com.longy.gulimall.product.service.CategoryService;
import com.longy.gulimall.product.vo.AttrGroupRelationVo;
import com.longy.gulimall.product.vo.AttrRespVo;
import com.longy.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longy.common.utils.Query;

import com.longy.gulimall.product.dao.AttrDao;
import com.longy.gulimall.product.entity.AttrEntity;
import com.longy.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrDao attrDao;

    @Resource
    private AttrGroupDao AttrGroupDao;

    @Resource
    private AttrAttrgroupRelationDao RelationDao;

    @Resource
    private CategoryDao CategoryDao;

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryBaseAttrList(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((queryWrapper) -> {
                wrapper.like("attr_name", key).or().eq("attr_id", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        //设置分组名和分类名
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo respVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, respVo);

            //设置分类名
            CategoryEntity categoryEntity = CategoryDao.selectById(respVo.getCatelogId());
            if (categoryEntity != null) {
                respVo.setAttrName(categoryEntity.getName());
            }

            //设置分组名
            AttrAttrgroupRelationEntity attrId = RelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", respVo.getAttrId()));
            if (attrId != null && attrId.getAttrGroupId()!=null) {
                Long attrGroupId = attrId.getAttrGroupId();

                AttrGroupEntity attrGroupEntity = AttrGroupDao.selectById(attrGroupId);
                respVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            return respVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        if(attrRespVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrRespVo.getAttrGroupId()!=null) {
            //设置组名
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = RelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrAttrgroupRelationEntity != null) {
                Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = AttrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrGroupId));
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息
        Long[] catelogPath = categoryService.findCatelogPath(attrRespVo.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = CategoryDao.selectById(attrRespVo.getCatelogId());
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
//        attrEntity.setAttrName(attr.getAttrName());
        BeanUtils.copyProperties(attr,attrEntity);
        //1、保存基本数据
        this.save(attrEntity);
        //2、保存关联关系
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            RelationDao.insert(relationEntity);
        }


    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        baseMapper.updateById(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null) {
            //修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            AttrAttrgroupRelationEntity relationEntity1 = RelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (relationEntity1 != null) {
                RelationDao.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                RelationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = RelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = relationEntities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if (attrIds!=null) {
            List<AttrEntity> attrEntities = attrDao.selectBatchIds(attrIds);
            return attrEntities;
        }
        return null;
    }

    @Override
    public void deleteAttrRelation(AttrGroupRelationVo[] vos) {
        //转换收集起来的AttrAttrgroupRelationEntity
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((vo) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        //调用方法一次批量删除
        RelationDao.deleteAttrRelation(collect);
    }

    @Override
    public PageUtils attrNoRelation(Long attrgroupId, Map<String, Object> params) {
        //1.当前分组只能关联自己所属分类里边的属性
        AttrEntity attrEntity = attrDao.selectById(attrgroupId);
        Long catelogId = attrEntity.getCatelogId();
        //2.当前分组只能关联别的分组没有引用的属性
        //2.1）当前分类的其他分组
        List<AttrGroupEntity> attrGroupEntity = AttrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<Long> collect = attrGroupEntity.stream().map((attr -> {
            return attr.getAttrGroupId();
        })).collect(Collectors.toList());

        //2.2）这些分组的属性
        List<AttrAttrgroupRelationEntity> relationEntities = RelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3）移除这些分组
        //构造分页查询
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id",catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds!=null && attrIds.size()> 0){
            wrapper.notIn("attr_id",attrIds);
        }
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("attr_id",key).or().like("attr_name",key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }



}